package com.cskaoyan.market.admin.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.cskaoyan.market.admin.service.MarketAdminAdService;
import com.cskaoyan.market.admin.service.impl.MarketAdminAdServiceImpl;
import com.cskaoyan.market.db.domain.MarketAd;
import com.cskaoyan.market.util.AdminResponseCode;
import com.cskaoyan.market.util.HttpUtil;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import com.github.pagehelper.util.StringUtil;

/**
 * @author James
 * @since 2023/03/21 16:20
 */
@WebServlet("/admin/ad/*")
public class AdminAdController extends HttpServlet {

    MarketAdminAdService adminAdService = new MarketAdminAdServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/ad/", "");
        if ("list".equals(op)) {
            list(req, resp);
        }
    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String pageParam = req.getParameter("page");
        String limitParam = req.getParameter("limit");
        String name = req.getParameter("name");
        String content = req.getParameter("content");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");
        // 判断
        if (StringUtils.isEmpty(pageParam) || StringUtil.isEmpty(limitParam)) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        // sort和order如果为空,则给他们设置一个默认值
        if (StringUtil.isEmpty(sort)) {
            sort = "add_time";
        }
        if (StringUtil.isEmpty(order)) {
            order = "desc";
        }
        int page = 0;
        int limit = 0;
        try {
            page = Integer.parseInt(pageParam);
            limit = Integer.parseInt(limitParam);
        } catch (NumberFormatException e) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        // 调用Service
        List<MarketAd> adList = adminAdService.list(page, limit, name, content, sort, order);
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.okList(adList)));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/ad/", "");
        if ("create".equals(op)) {
            create(req, resp);
        } else if ("update".equals(op)) {
            update(req, resp);
        } else if ("delete".equals(op)) {
            delete(req, resp);
        }
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = HttpUtil.getRequestBody(req);
        String addTime = JacksonUtil.parseString(requestBody, "addTime");
        String content = JacksonUtil.parseString(requestBody, "content");
        Boolean delete = JacksonUtil.parseBoolean(requestBody, "delete");
        Boolean enabled = JacksonUtil.parseBoolean(requestBody, "enabled");
        int id = JacksonUtil.parseInteger(requestBody, "id");
        String link = JacksonUtil.parseString(requestBody, "link");
        String name = JacksonUtil.parseString(requestBody, "name");
        Byte position = JacksonUtil.parseByte(requestBody, "position");
        String updateTime = JacksonUtil.parseString(requestBody, "updateTime");
        String url = JacksonUtil.parseString(requestBody, "url");

        if (StringUtils.isEmpty(content)) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        adminAdService.delete(addTime, content, delete, enabled, id, link, name, position, updateTime, url);
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok()));
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = HttpUtil.getRequestBody(req);
        String addTime = JacksonUtil.parseString(requestBody, "addTime");
        String content = JacksonUtil.parseString(requestBody, "content");
        Boolean deleted = JacksonUtil.parseBoolean(requestBody, "deleted");
        Boolean enabled = JacksonUtil.parseBoolean(requestBody, "enabled");
        Integer id = JacksonUtil.parseInteger(requestBody, "id");
        String link = JacksonUtil.parseString(requestBody, "link");
        String name = JacksonUtil.parseString(requestBody, "name");
        Byte position = JacksonUtil.parseByte(requestBody, "position");
        String updateTime = JacksonUtil.parseString(requestBody, "updateTime");
        String url = JacksonUtil.parseString(requestBody, "url");

        if (StringUtil.isEmpty(name) || StringUtil.isEmpty(content) || StringUtil.isEmpty(link)) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        // 调用Service
        MarketAd marketAd =
            adminAdService.update(addTime, content, deleted, enabled, id, link, name, position, updateTime, url);
        HashMap<Object, Object> data = getResponseBody(marketAd);
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok(data)));
    }

    private void create(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String requestBody = HttpUtil.getRequestBody(req);
        String content = JacksonUtil.parseString(requestBody, "content");
        boolean enabled = JacksonUtil.parseBoolean(requestBody, "enabled");
        String link = JacksonUtil.parseString(requestBody, "link");
        String name = JacksonUtil.parseString(requestBody, "name");
        Byte position = JacksonUtil.parseByte(requestBody, "position");
        String url = JacksonUtil.parseString(requestBody, "url");

        // 判断哪些是必须的内容
        if (StringUtil.isEmpty(content) || StringUtil.isEmpty(name) /*|| StringUtil.isEmpty(url)*/) {
            resp.getWriter().println(
                JacksonUtil.writeValueAsString(ResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_NAME, "必要属性不能为空")));
            return;
        }
        MarketAd marketAd = adminAdService.create(content, enabled, link, name, position, url);

        HashMap<Object, Object> data = getResponseBody(marketAd);
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok(data)));
    }

    private HashMap<Object, Object> getResponseBody(MarketAd marketAd) {
        HashMap<Object, Object> data = new HashMap<>();
        data.put("addTime", marketAd.getAddTime());
        data.put("content", marketAd.getContent());
        data.put("enabled", marketAd.getEnabled());
        data.put("id", marketAd.getId());
        data.put("link", marketAd.getLink());
        data.put("name", marketAd.getName());
        data.put("position", marketAd.getPosition());
        data.put("updateTime", marketAd.getUpdateTime());
        data.put("url", marketAd.getUrl());
        return data;
    }

}